/**
 * 采购订单id
 *
 * @type {null}
 */
let procurementOrderId = UrlUtils.getUrlParam("id");

/**
 * 产品列表
 * @type {null}
 */
let products = null;

/**
 * 创建人
 */
let creator;

/**
 * 提交人
 */
let submitter;

/**
 * 复核人
 */
let reviewer;

/**
 * 审批人
 */
let approver;

/**
 * 采购单当前处理人
 * @type {null}
 */
let currentHandler = null;

/**
 * 采购订单状态
 * @type {null}
 */
let procurementOrderStatus = null;

/**
 * 状态map
 */
let statusMap = {
    "0": "draft",
    "1": "review",
    "2": "approve",
    "3": "complete"
}

/**
 * 查询基本信息
 */
function findProcurementOrder() {
    $.ajax({
        type: 'GET',
        contentType: "application/json;charset=UTF-8",
        url: "/service/workflow/procurement/findProcurementOrder/" + procurementOrderId,
        async: false,
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        success: function (data) {
            procurementOrderStatus = data.status;
            currentHandler = data.currentHandler;

            $(".procurement-component .base-info .status-element").show();

            $(".procurement-component .base-info .status-value").val(statusMap[data.status]);
            $(".procurement-component .base-info .code").text(data.code);
            $(".procurement-component .base-info .name-value").val(data.name);
            $(".procurement-component .base-info .description-value").val(data.description);

            if (procurementOrderStatus != 0 || currentHandler != FrontInfoUtils.getCurrentUserInfo().username) {
                $(".procurement-component .base-info input, .procurement-component .base-info textarea").attr("disabled", true);
                $(".procurement-component .base-info .save-button").hide();
                $(".procurement-component .item-div .item-add-button").hide();
            }
            else {
                $(".procurement-component .base-info input, .procurement-component .base-info textarea").attr("disabled", false);
                $(".procurement-component .base-info .save-button").show();
                $(".procurement-component .item-div .item-add-button").show();
            }

            creator = data.creator;
            submitter = data.submitter;
            reviewer = data.reviewer;
            approver = data.approver;
        }
    });
}

/**
 * 查询采购订单明细
 *
 */
function queryProcurementItems() {
    $.ajax({
        type: 'GET',
        contentType: "application/json;charset=UTF-8",
        url: "/service/workflow/procurement/queryProcurementItems/" + procurementOrderId,
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        success: function (data) {
            $(".procurement-component .item-div .item-list").empty();
            for (let i = 0; i < data.length; i++) {
                let procurementItem = data[i];
                let procurementItemPanel = $(".procurement-component .templates .procurement-item-panel").clone();
                procurementItemPanel.find(".code").text(procurementItem.code);
                procurementItemPanel.find(".name").text(procurementItem.name);
                procurementItemPanel.find(".count").text(procurementItem.count);

                let modifyButton = procurementItemPanel.find(".modify-button");
                modifyButton.click(function () {
                    handleModifyProcurementItemButtonClick(procurementItemPanel, procurementItem);
                });

                let deleteButton = procurementItemPanel.find(".delete-button");
                deleteButton.click(function () {
                    PromptWindowUtils.showDeletePrompt("Are you sure to delete this procurement item?", function () {
                        $.ajax({
                            type: 'DELETE',
                            async: false,
                            contentType: "application/json;charset=UTF-8",
                            url: "/service/workflow/procurement/deleteProcurementItem/" + procurementItem.id,
                            headers: {
                                Authorization: JwtTokenUtils.getBearerHeader()
                            },
                            success: function () {
                                queryProcurementItems();
                                PromptWindowUtils.hideDeletePrompt();
                            }
                        });
                    });
                });

                if (procurementOrderStatus != 0 || currentHandler != FrontInfoUtils.getCurrentUserInfo().username) {
                    modifyButton.css("display", "none");
                    deleteButton.css("display", "none");
                }
                else {
                    modifyButton.css("display", "inline-block");
                    deleteButton.css("display", "inline-block");
                }

                $(".procurement-component .item-div .item-list").append(procurementItemPanel);
            }
        }
    });
}

/**
 * 查询流程记录
 *
 */
function queryProcessRecords() {
    $.ajax({
        type: 'GET',
        contentType: "application/json;charset=UTF-8",
        url: "/service/workflow/procurement/queryProcessRecords/" + procurementOrderId,
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        success: function (data) {
            $(".procurement-component .process-records-div .item-list").empty();
            for (let i = 0; i < data.length; i++) {
                let processRecord = data[i];
                let processRecordPanel = $(".procurement-component .templates .process-record-panel").clone();
                processRecordPanel.find(".created-date").text(DateUtils.format(new Date(processRecord.createdDate), "yyyy-MM-dd hh:mm:ss"));
                processRecordPanel.find(".handler").text(processRecord.handler);
                processRecordPanel.find(".status").text(statusMap[processRecord.status]);
                let operateMap = {
                    "1": "ACCEPT",
                    "-1": "REJECT",
                    "-2": "WITHDRAW"
                }
                processRecordPanel.find(".operate").text(operateMap[processRecord.operate]);
                processRecordPanel.find(".content").text(processRecord.content);
                $(".procurement-component .process-records-div .item-list").append(processRecordPanel);
            }
        }
    });
}

/**
 * procurement item的修改按钮点击事件
 *  
 * @param {*} procurementItemPanel procurement item panel
 * @param {*} procurementItem procurement item数据
 */
function handleModifyProcurementItemButtonClick(procurementItemPanel, procurementItem) {
    let editProcurementItemPanel = $(".component .templates .edit-item-panel").clone();
    renderProducts(editProcurementItemPanel);
    editProcurementItemPanel.attr("id", procurementItem.id);
    editProcurementItemPanel.find(".code-element").text(procurementItem.code);
    editProcurementItemPanel.find(".count-value").val(procurementItem.count);
    editProcurementItemPanel.find(".dropdown .selected-item").text(procurementItem.name);
    editProcurementItemPanel.insertAfter(procurementItemPanel.children(".self"));

    editProcurementItemPanel.find(".cancel-button").click(function () {
        editProcurementItemPanel.remove();
    });

    editProcurementItemPanel.find(".save-button").click(function () {
        let requestData = {
            id: procurementItem.id,
            code: editProcurementItemPanel.find(".code-element").text(),
            name: editProcurementItemPanel.find(".dropdown .selected-item").text(),
            count: editProcurementItemPanel.find(".count-value").val()
        };
        $.ajax({
            type: "POST",
            contentType: "application/json;charset=utf-8",
            url: "/service/workflow/procurement/saveProcurementItem",
            dataType: "json",
            headers: {
                Authorization: JwtTokenUtils.getBearerHeader()
            },
            data: JSON.stringify(requestData),
            success: function () {
                editProcurementItemPanel.remove();
                queryProcurementItems();
            }
        });
    });
}

/**
 * 获取产品列表
 */
function queryProducts() {
    $.ajax({
        type: 'GET',
        async: false,
        contentType: "application/json;charset=UTF-8",
        url: "/service/datacenter/lookup/querySingleLookup/product",
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        success: function (data) {
            products = data.lookupItems;
        }
    });
}

/**
 * 渲染产品下拉列表
 *
 * @param panel panel
 */
function renderProducts(panel) {
    for (let i = 0; i < products.length; i++) {
        let product = products[i];
        let li = $("<li></li>");
        let span = $("<span></span>")
        span.text(product.name);
        li.append(span);
        li.attr("code", product.code);
        li.click(function () {
            panel.find(".selected-item").text(product.name);
            panel.find(".code-element").text(product.code);
        });
        panel.find(".product-list").append(li);
    }
}

/**
 * 渲染复核人
 */
function renderReviewers() {
    $.ajax({
        type: 'GET',
        async: false,
        contentType: "application/json;charset=UTF-8",
        url: "/service/datacenter/lookup/querySingleLookup/reviewer",
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        success: function (data) {
            let reviewers = data.lookupItems;
            for (let i = 0; i < reviewers.length; i++) {
                let reviewer = reviewers[i];
                let li = $("<li></li>");
                let span = $("<span></span>");
                span.text(reviewer.name);
                li.attr("code", reviewer.code);
                li.append(span);
                li.click(function () {
                    $(".procurement-component .submit-div .reviewer-input .selected-item").text(reviewer.name);
                    $(".procurement-component .submit-div .reviewer-input").attr("code", reviewer.code);
                });
                $(".procurement-component .submit-div .reviewer-element .reviewer-list").append(li);
            }
        }
    });
}

/**
 * 渲染审批人
 */
function renderApprovers() {
    $.ajax({
        type: 'GET',
        async: false,
        contentType: "application/json;charset=UTF-8",
        url: "/service/datacenter/lookup/querySingleLookup/approver",
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        success: function (data) {
            let approvers = data.lookupItems;
            for (let i = 0; i < approvers.length; i++) {
                let approve = approvers[i];
                let li = $("<li></li>");
                let span = $("<span></span>");
                span.text(approve.name);
                li.attr("code", approve.code);
                li.append(span);
                li.click(function () {
                    $(".procurement-component .review-div .approver-input .selected-item").text(approve.name);
                    $(".procurement-component .review-div .approver-input").attr("code", approve.code);
                });
                $(".procurement-component .handle-div .approver-element .approver-list").append(li);
            }
        }
    });
}

/**
 * 初始化页面
 *
 * 根据采购订单状态显示页面不同部位
 *
 * 如果采购顶顶那已经保存，则显示采购明细列表
 * 处理模块，审批记录模块
 *
 * 如果是草稿状态，则显示提交表单
 * 如果是复核状态，则显示复核表单
 * 如果是审批状态，则显示审批表单
 *
 */
function init() {
    let currentUser = FrontInfoUtils.getCurrentUserInfo().username;
    if (typeof procurementOrderId != "undefined" && procurementOrderId != null) {
        findProcurementOrder();
        queryProcurementItems();
        queryProcessRecords();

        if (typeof procurementOrderStatus != "undefined" && procurementOrderStatus != null) {
            $(".procurement-component .item-div").addClass("show");
            if (procurementOrderStatus != 3) {
                $(".procurement-component .handle-div").addClass("show");
            }
            $(".procurement-component .process-records-div").addClass("show");
        }

        $(".procurement-component .submit-div").removeClass("show");
        $(".procurement-component .review-div").removeClass("show");
        $(".procurement-component .approve-div").removeClass("show");

        if (procurementOrderStatus == 0) {
            if (currentUser == currentHandler) {
                $(".procurement-component .submit-div").addClass("show");
                $(".procurement-component .submit-div .submit-button").addClass("show");
                $(".procurement-component .submit-div .reset-button").addClass("show");
                renderReviewers();
                $(".procurement-component .submit-div .reviewer-wrap").addClass("show");
            }
        }
        if (procurementOrderStatus == 1) {
            if (currentUser == currentHandler) {
                $(".procurement-component .review-div").addClass("show");
                renderApprovers();
            }
            else if (currentUser == submitter) {
                $(".procurement-component .submit-div").addClass("show");
                $(".procurement-component .submit-div .withdraw-button").addClass("show");
            }
        }
        if (procurementOrderStatus == 2) {
            if (currentUser == currentHandler) {
                $(".procurement-component .approve-div").addClass("show");
            }
        }
    }
}

/**
 * 页面启动完成事件
 *
 */
$(document).ready(function () {

    queryProducts();

    renderProducts($(".procurement-component .add-product-item-panel"));

    init();

    /**
     * 保存订单按钮点击
     */
    $(".procurement-component .base-info .save-button").click(function () {
        let requestData = {
            name: $(".procurement-component .base-info .name-value").val(),
            description: $(".procurement-component .base-info .description-value").val(),
            id: procurementOrderId
        };
        $.ajax({
            type: 'POST',
            url: "/service/workflow/procurement/saveProcurementOrder",
            contentType: "application/json;charset=UTF-8",
            headers: {
                Authorization: JwtTokenUtils.getBearerHeader()
            },
            data: JSON.stringify(requestData),
            success: function (ret) {
                if (typeof procurementOrderId == "undefined" || procurementOrderId == null) {
                    procurementOrderId = ret.data;
                    $(".procurement-component .item-div").addClass("show");
                    $(".procurement-component .handle-div").addClass("show");
                    $(".procurement-component .process-records-div").addClass("show");
                    init();
                }
            }
        });
    });

    /**
     * 添加产品按钮点击事件
     */
    $(".procurement-component .add-product-button").click(function () {
        $(".procurement-component .add-product-item-panel").addClass("show");
    });

    /**
     * 添加窗口关闭按钮点击
     */
    $(".procurement-component .add-item-panel .close-button").click(function () {
        $(".procurement-component .add-product-item-panel").removeClass("show");
    });

    /**
     * 添加产品窗口保存按钮点击
     */
    $(".procurement-component .add-item-panel .ok-button").click(function () {
        let requestData = {
            code: $(".procurement-component .add-product-item-panel .code-element").text(),
            name: $(".procurement-component .add-product-item-panel .name-element .selected-item").text(),
            count: $(".procurement-component .add-product-item-panel .count-value").val(),
            procurementOrderId: procurementOrderId
        };
        $.ajax({
            type: 'POST',
            url: "/service/workflow/procurement/saveProcurementItem",
            contentType: "application/json;charset=UTF-8",
            headers: {
                Authorization: JwtTokenUtils.getBearerHeader()
            },
            data: JSON.stringify(requestData),
            success: function () {
                queryProcurementItems();
            }
        });
    });

    /**
     * 添加窗口重置按钮点击
     */
    $(".procurement-component .add-item-panel .reset-button").click(function () {
        $(".procurement-component .add-product-item-panel .code-element").text("");
        $(".procurement-component .add-product-item-panel .name-element .selected-item").text("product");
        $(".procurement-component .add-product-item-panel .count-value").text("");
    });

    /**
     * 提交按钮点击事件
     */
    $(".procurement-component .handle-div .submit-div .submit-button").click(function () {
        let requestData = {
            id: procurementOrderId,
            reviewer: $(".procurement-component .handle-div .reviewer-input").attr("code")
        };
        $.ajax({
            type: 'POST',
            url: "/service/workflow/procurement/submitProcurementOrder",
            contentType: "application/json;charset=UTF-8",
            headers: {
                Authorization: JwtTokenUtils.getBearerHeader()
            },
            data: JSON.stringify(requestData),
            success: function (data) {
                location.href = "procurement-list.html";
            }
        });
    })

    /**
     * 撤回按钮点击事件
     */
    $(".procurement-component .handle-div .submit-div .withdraw-button").click(function () {
        $.ajax({
            type: 'POST',
            url: "/service/workflow/procurement/withdrawProcurementOrder/" + procurementOrderId,
            contentType: "application/json;charset=UTF-8",
            headers: {
                Authorization: JwtTokenUtils.getBearerHeader()
            },
            success: function (data) {
                location.href = "procurement-list.html";
            }
        });
    });

    /**
     * review窗口中的accept按钮点击事件
     */
    $(".procurement-component .review-div .accept-button").click(function () {
        let requestData = {
            id: procurementOrderId,
            operate: 1,
            approver: $(".procurement-component .handle-div .approver-input").attr("code"),
            comment: $(".procurement-component .review-div .comment-value").val()
        };
        $.ajax({
            type: 'POST',
            url: "/service/workflow/procurement/reviewProcurementOrder",
            contentType: "application/json;charset=UTF-8",
            headers: {
                Authorization: JwtTokenUtils.getBearerHeader()
            },
            data: JSON.stringify(requestData),
            success: function (data) {
                location.href = "procurement-list.html";
            }
        });
    });

    /**
     * review窗口中重置按钮点击事件
     */
    $(".procurement-component .review-div .reset-button").click(function () {
        $(".procurement-component .review-div .comment-value").val("");
        $(".procurement-component .review-div .approver-input").removeAttr("code");
        $(".procurement-component .review-div .approver-input .selected-item").text("reviewer");
    });

    /**
     * approve窗口中的accept按钮点击事件
     */
    $(".procurement-component .approve-div .accept-button").click(function () {
        let requestData = {
            id: procurementOrderId,
            operate: 1,
            comment: $(".procurement-component .approve-div .comment-value").val()
        };
        $.ajax({
            type: 'POST',
            url: "/service/workflow/procurement/approveProcurementOrder",
            contentType: "application/json;charset=UTF-8",
            headers: {
                Authorization: JwtTokenUtils.getBearerHeader()
            },
            data: JSON.stringify(requestData),
            success: function (data) {
                location.href = "procurement-list.html";
            }
        });
    });

    /**
     * approve窗口中重置按钮点击事件
     */
    $(".procurement-component .approve-div .reset-button").click(function () {
        $(".procurement-component .approve-div .comment-value").text("");
        $(".procurement-component .approve-div .approver-input").removeAttr("code");
        $(".procurement-component .approve-div .count-value").text("");
    });

}
);